"use client"

import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { signIn } from "next-auth/react"
import Link from "next/link"
import { useState } from "react"

export default function RegisterPage() {
  const [error, setError] = useState<string>("")
  const [loading, setLoading] = useState(false)

  async function onSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault()
    setLoading(true)
    setError("")

    const formData = new FormData(event.currentTarget)
    const username = formData.get("username") as string
    const password = formData.get("password") as string
    const confirmPassword = formData.get("confirmPassword") as string

    if (password !== confirmPassword) {
      setError("两次输入的密码不一致")
      setLoading(false)
      return
    }

    const res = await fetch("/api/register", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        username,
        password,
      }),
    })

    const data = await res.json()

    if (!res.ok) {
      setError(data.error || "注册失败")
      setLoading(false)
      return
    }

    // 注册成功后直接登录
    await signIn("credentials", {
      username,
      password,
      callbackUrl: "/",
    })
  }

  return (
    <div className="flex min-h-screen items-center justify-center">
      <div className="w-full max-w-md space-y-8 px-4">
        <div className="text-center">
          <h1 className="text-2xl font-bold">注册</h1>
          <p className="mt-2 text-gray-600">创建新账号</p>
        </div>

        <form onSubmit={onSubmit} className="space-y-4">
          <div>
            <Input
              name="username"
              type="text"
              placeholder="用户名"
              required
            />
          </div>

          <div>
            <Input
              name="password"
              type="password"
              placeholder="密码"
              required
            />
          </div>

          <div>
            <Input
              name="confirmPassword"
              type="password"
              placeholder="确认密码"
              required
            />
          </div>

          {error && (
            <p className="text-sm text-red-500">{error}</p>
          )}

          <Button
            type="submit"
            className="w-full"
            disabled={loading}
          >
            {loading ? "注册中..." : "注册"}
          </Button>

          <p className="text-center text-sm text-gray-600">
            已有账号？{" "}
            <Link href="/auth/login" className="text-blue-600 hover:underline">
              登录
            </Link>
          </p>
        </form>
      </div>
    </div>
  )
} 